package com.jzbooks.Interceptor;

import com.alibaba.fastjson.JSONObject;
import com.jzbooks.enums.ResultCodeEnum;
import com.jzbooks.exception.BusinessException;
import com.jzbooks.result.ErrorResult;
import com.jzbooks.utils.JwtUtil;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.util.List;

import static org.springframework.http.MediaType.APPLICATION_JSON;

/**
 * @author mingPeng
 * @date 2021/4/26 17:02
 * @Description : 拦截请求 验证 token
 */
@Component
@Slf4j
@Getter
@Setter
public class TokenInterceptor implements HandlerInterceptor {

    @Value("${interceptor.includePathPatterns}")
    private List<String> includePathPatterns;

    @Value("${interceptor.excludePathPatterns}")
    private List<String> excludePathPatterns;

    /**
     * 请求头
     */
    @Value("${jwt.tokenHeaderName}")
    private String tokenHeaderName;

    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String queryStr = String.format("Query: URI: %s ContextPath: %s QueryString: %s method: %s Token: %s"
                , request.getRequestURI()
                , request.getContextPath()
                , request.getQueryString()
                , request.getMethod()
                , request.getHeader(tokenHeaderName)
        );
        log.info(queryStr);

        if (HttpMethod.OPTIONS.toString().equals(request.getMethod())) {
            System.out.println("OPTIONS请求，放行");
            return true;
        }

        if (!jwtUtil.verifyJWTAndRefreshExpireTime(request,response)){
            log.info("没有token");
//            response.setStatus(HttpStatus.SC_ok);
            response.setContentType(APPLICATION_JSON.toString());
            response.setCharacterEncoding(StandardCharsets.UTF_8.name());
            String responseBodyText = JSONObject.toJSONString(ErrorResult.failure(
                    new BusinessException(ResultCodeEnum.ILLEGAL_TOKEN)));
            PrintWriter pw = response.getWriter();
            pw.write(responseBodyText);
            pw.flush();
            pw.close();
            return false;
        }

        return true;
    }
}
